using System;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;

namespace MM.Translator.Model
{
    public class GoogleTranslationProvider : ITranslationProvider
    {
        public void Translate(string inputText, string fromLanguage, string toLanguage)
        {
            var url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + inputText + "&langpair=" + fromLanguage + "%7C" + toLanguage;

            var webClient = new WebClient { Encoding = Encoding.UTF8 };
            webClient.DownloadStringCompleted += OnDownloadStringCompleted;
            webClient.DownloadStringAsync(new Uri(url));
        }

        private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (TranslationCompleted != null)
            {
                if (e.Error != null)
                {
                    TranslationCompleted(this, new TranslationEventArgs() {Error = e.Error});
                    return;
                }

                var result = e.Result;
                var jObject = JObject.Parse(result);
                var selectToken = jObject.SelectToken("responseData.translatedText");

                TranslationCompleted(this, new TranslationEventArgs { Result = selectToken != null ? selectToken.ToString().Replace("\"", "") : string.Empty });
            }
        }

        public event EventHandler<TranslationEventArgs> TranslationCompleted;
    }
}